package com.senyint.imsdk.packet;

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.jivesoftware.smack.packet.PacketExtension;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class SimpleEventExtension implements PacketExtension {
	public static final String TAG = SimpleEventExtension.class.getSimpleName();
	
	public final static String ELEMENT_NAME = "e";
    public static final String NAMESPACE = "urn:syt:e";
    
    private String type ;
	private String event ;
	
	public SimpleEventExtension() {
	}
	
	public SimpleEventExtension(String type, String event) {
		this.type = type ;
		this.event = event ;
	}
	
	public String getType() {
		return type;
	}

	public String getEvent() {
		return event;
	}

	@Override
	public String getElementName() {
		return ELEMENT_NAME;
	}
	
	@Override
	public String getNamespace() {
		return NAMESPACE;
	}
	
	@Override
	public String toXML() {
        StringBuffer sb = new StringBuffer();
        sb.append("<").append(ELEMENT_NAME).append(" xmlns=\"").append(NAMESPACE).append("\">");
        sb.append("<type>").append(type).append("</type>");
        sb.append("<event>").append(event).append("</event>");
        sb.append("</"+ELEMENT_NAME+">");

        return sb.toString();
	}

    public static SimpleEventExtension parse(String xml) {
        SimpleEventExtension  pe = new SimpleEventExtension();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new ByteArrayInputStream(xml.getBytes()));
            Element root = document.getDocumentElement();
            NodeList nodeList = root.getChildNodes();
            int size = nodeList.getLength();
            for (int i = 0; i < size; i++) {
                Node node = nodeList.item(i);
                String nodeName = node.getNodeName();
                String value = node.getTextContent();
                if (nodeName.equals("type")) {
                	pe.type = value;
                } else if (nodeName.equals("event")) {
                	pe.event= value;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return pe;
    }
    
}
